import {
  ChangeDetectionStrategy,
  Component,
  Input, ViewEncapsulation
} from '@angular/core';

import {InputBoolean, toBoolean} from '../core/util/convert';

import { ApesCollapsePanelComponent } from './apes-collapse-panel.component';
import {ApesConfigService, WithConfig} from "@shared/apes/core";

@Component({
  selector   : 'apes-collapse',
  exportAs: 'apesCollapse',
  templateUrl: './apes-collapse.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  styles     : [
    `apes-collapse {
      display: block;
    }`
  ]
})
export class ApesCollapseComponent {
  prefixCls='apes-collapse';
  private listOfApesCollapsePanelComponent: ApesCollapsePanelComponent[] = [];
  @Input() @WithConfig(false) @InputBoolean() apesAccordion: boolean;
  @Input() @WithConfig(true) @InputBoolean() apesBordered: boolean;

  constructor(public apesConfigService: ApesConfigService) {}

  addPanel(value: ApesCollapsePanelComponent): void {
    this.listOfApesCollapsePanelComponent.push(value);
  }

  removePanel(value: ApesCollapsePanelComponent): void {
    this.listOfApesCollapsePanelComponent.splice(this.listOfApesCollapsePanelComponent.indexOf(value), 1);
  }

  click(collapse: ApesCollapsePanelComponent): void {
    if (this.apesAccordion && !collapse.apesActive) {
      this.listOfApesCollapsePanelComponent
        .filter(item => item !== collapse)
        .forEach(item => {
          if (item.apesActive) {
            item.apesActive = false;
            item.apesActiveChange.emit(item.apesActive);
            item.markForCheck();
          }
        });
    }
    collapse.apesActive = !collapse.apesActive;
    collapse.apesActiveChange.emit(collapse.apesActive);
  }
}
